﻿using CPPEI.Coolzon.DataTask;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.DataTask
{
    /// <summary>
    /// 加载数据任务池
    /// </summary>
    public class DataLoadTaskPool
    {
        private DataLoadTaskPool() { _taskQueue = new List<DataLoadTask>(); }

        private static DataLoadTaskPool s_instance;
        private static object s_lockObj = new object();

        /// <summary>
        /// 单例模式
        /// </summary>
        public static DataLoadTaskPool Instance
        {
            get
            {
                if (s_instance == null)
                {
                    lock (s_lockObj)
                    {
                        if (s_instance == null)
                        {
                            s_instance = new DataLoadTaskPool();
                        }
                    }

                }
                return s_instance;
            }
        }

        private List<DataLoadTask> _taskQueue;

        /// <summary>
        /// 添加任务或在任务中添加组件
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public AddOrUpdateTaskResult AddOrUpdateTask(DataLoadTask task)
        {
            lock (_taskQueue)
            {
                foreach (DataLoadTask dataLoadTask in _taskQueue)
                {
                    if (dataLoadTask.Identity == task.Identity)
                    {
                        dataLoadTask.AddListDataPart(task.RelateParts);
                        return AddOrUpdateTaskResult.Update;
                    }
                }

                _taskQueue.Add(task);
                return AddOrUpdateTaskResult.Add;
            }
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public bool RemoveTask(DataLoadTask task)
        {
            lock (_taskQueue)
            {
                for (int i = 0; i < _taskQueue.Count; i++)
                {
                    if (_taskQueue[i].Identity == task.Identity)
                    {
                        _taskQueue.RemoveAt(i);
                        return true;
                    }
                }
                return false;
            }
        }

        /// <summary>
        /// 添加或更新任务结果
        /// </summary>
        public enum AddOrUpdateTaskResult
        {
            Add,
            Update,
        }
    }
}
